var app = getApp()
import timeDateChoose from '../../utils/components/timeDatePicker/index'
import _config from '../../utils/config';
import _fetch from '../../utils/httpService';
import util from '../../utils/util';

Page({
  data: {
    form: {
      isFill: 0,
      cusIndex: null
    },
    projectIndex: null,
    projectList: [],
    templateId: '',
    applyLocationShow: false,
    isChange: false,
    templateName: '',
    phoneValue: null,
    cusName: null
  },
  onLoad: function (options) {
    // 生命周期函数--监听页面加载
    let templateId = options.id
    let time = timeDateChoose.timeOnLoad()
    this.setData({
      'form.dateTimeMin': time.dateTimeMin,
      'form.dateTimeArrayMin': time.dateTimeArrayMin,
      'form.dateTimeUnitArr': time.dateTimeUnitArrayMin,
      templateId: templateId,
      templateName: options.name
    })
    if (options.form) {
      this.setData({
        'form.enter': 'add',
        'form.formList': JSON.parse(options.form),
        'form.disabled': false,
        'form.cusIndex': Number(options.cusindex) || null,
        phoneValue: options.phone,
        cusName: options.cusname
      })
    } else {
      this.init(options.id)
    }
    wx.setNavigationBarTitle({
      title: `${options.name}`
    })
  },
  onReady: function () {
    // this.mapCtx = wx.createMapContext('map')
  },
  onShow: function () {
    // 生命周期函数--监听页面显示
    // this.getDetail(this.data.templateId)
  },
  onHide: function () {
    // 生命周期函数--监听页面隐藏
  },
  onUnload: function () {
    // 生命周期函数--监听页面卸载
  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
  },
  onReachBottom: function () {
    // 页面上拉触底事件的处理函数
  },
  onShareAppMessage: function () {
    // 用户点击右上角分享
    return {
      title: '助力企业工单管理智能升级', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index', // 分享路径
      imageUrl: '../../img/Mask.png' // 分享图片
    }
  },
  init(id) {
    this.getProgressList(id)
    setTimeout(() => {
      this.getDetail(id)
    }, 300);

  },
  getProgressList(id) {
    let url = _config.url.get_server_list_by_temp.replace('{id}', id)
    _fetch.get(url).then(res => {
      this.data.projectList = res
    }).catch(error => {
      wx.showToast({
        title: error.smg,
        icon: 'none',
      });
    })
  },
  getDetail(id) {
    // 模版详情
    let vm = this
    let url = _config.url.get_template_item_info.replace('{id}', id)
    _fetch.get(url).then(function (data) {
      if (data && data.length) {
        let result = data.map((i, idx) => {
          if (i.componentType === 1 && i.title === '详细地址') {
            i.sync = false
          }
          if ((i.componentType === 3 || i.componentType === 4 || i.componentType === 21) && i.optValue && i.optValue.length > 0) {
            // 单选、多选数据处理
            let jtemp = [],
              value
            if (i.componentValue) {
              if (i.componentType === 3 || i.componentType === 21) {
                value = i.componentValue
                jtemp = i.optValue.map(j => {
                  if (value === j) {
                    return {
                      name: j,
                      checked: true
                    }
                  } else {
                    return {
                      name: j,
                      checked: false
                    }
                  }
                })
              } else {
                value = JSON.parse(i.componentValue)
                jtemp = i.optValue.map(j => {
                  return {
                    name: j,
                    checked: value.includes(j)
                  }
                })
              }
            } else {
              jtemp = i.optValue.map(j => {
                return {
                  name: j,
                  checked: false
                }
              })
            }
            i.checkList = jtemp
          }
          if (i.componentType === 6) {
            // 图片数据处理
            if (i.componentValue) {
              i.componentValue = i.componentValue.split(',')
            } else {
              i.componentValue = []
            }
          }
          if (i.componentType === 7) {
            // 时间数据处理
            i.dateTimeMin = vm.data.form.dateTimeMin
          }
          if (i.componentType === 8) {
            // 地址数据处理
            if (i.componentValue) {
              let obj = JSON.parse(i.componentValue)
              if (obj.addressType === 0) {
                i.region = []
                i.componentValue = {
                  addressType: obj.addressType,
                  addressValue: {
                    adCode: obj.addressValue.adCode,
                    latitude: obj.addressValue.latitude,
                    longitude: obj.addressValue.longitude,
                    location: obj.addressValue.location
                  }
                }
              } else {
                i.region = [obj.addressValue.provinceName, obj.addressValue.cityName, obj.addressValue.areaName]
                i.componentValue = {
                  addressType: obj.addressType,
                  addressValue: {
                    provinceName: obj.addressValue.provinceName,
                    cityName: obj.addressValue.cityName,
                    areaName: obj.addressValue.areaName,
                    provinceId: obj.addressValue.provinceId,
                    cityId: obj.addressValue.cityId,
                    areaId: obj.addressValue.areaId
                  }
                }
              }
            } else {
              i.region = []
              i.componentValue = {
                addressValue: {}
              }
            }
          }
          if (i.componentType === 20) {
            i.checkList = vm.data.projectList
            if (i.componentValue) {
              let obj = JSON.parse(i.componentValue)
              vm.data.projectList.map(j => {
                if (obj.serviceProjectId === j.serviceProjectId) {
                  i.showText = j.projectName
                }
              })
            }
          }
          if (i.componentType === 22) {
            vm.data.form.cusIndex = idx
            if (i.componentValue) {
              i.componentValue = JSON.parse(i.componentValue)
            } else {
              i.componentValue = {
                sync: false,
                customerId: null,
                customerName: null
              }
            }
          }
          return i
        })
        vm.setData({
          'form.enter': 'add',
          'form.formList': result,
          'form.disabled': false,
          'form.cusIndex': vm.data.form.cusIndex
        })
      }
    }).catch(function (error) {
      wx.showToast({
        title: error.msg,
        icon: 'none',
      });
    });
  },
  inputText(e) {
    //文本输入
    let vm = this
    if (e.detail.value && e.currentTarget.dataset.iindex !== null && e.currentTarget.dataset.iindex !== undefined) {
      let index = e.currentTarget.dataset.iindex
      this.data.form.formList[index].componentValue = e.detail.value
      if (this.data.form.formList[index].title == '联系电话') {
        this.setData({
          phoneValue: e.detail.value || null
        })
      }
      this.setData({
        'form.formList': vm.data.form.formList,
      })
    }
  },
  inputCustom(e) {
    let vm = this
    if (e.detail.value && e.currentTarget.dataset.iindex !== null && e.currentTarget.dataset.iindex !== undefined) {
      let index = e.currentTarget.dataset.iindex
      this.data.form.formList[index].componentValue.customerName = e.detail.value
      this.setData({
        'form.formList': vm.data.form.formList,
        cusName: e.detail.value || null
      })
    }
  },
  toCustom(e) {
    let index = e.currentTarget.dataset.iindex
    wx.navigateTo({
      url: `../customer/index?form=${JSON.stringify(this.data.form.formList)}&index=${index}&id=${this.data.templateId}&name=${this.data.templateName}&enter=order&cusindex=${this.data.form.cusIndex}`
    })
  },
  tapOut() {},
  checkCustomChange(e) {
    let index = e.currentTarget.dataset.iindex,
      value = this.data.form.formList[index] || {},
      cusValue = this.data.form.formList[this.data.form.cusIndex].componentValue,
      sync = e.detail.value.length > 0
    value = Object.assign(value, {
      sync: sync
    })
    cusValue = Object.assign(cusValue, {
      sync: sync
    })
    // this.data.form.formList[index].componentValue = value
    this.data.form.formList[index] = value
    this.data.form.formList[this.data.form.cusIndex].componentValue = cusValue
    this.setData({
      isChange: true,
      'form.formList': this.data.form.formList
    })
    setTimeout(() => {
      this.setData({
        isChange: false
      })
    }, 500)
  },
  tapCustom(e) {
    let index = e.currentTarget.dataset.iindex,
      sync = e.currentTarget.dataset.sync,
      value = this.data.form.formList[index] || {},
      cusValue = this.data.form.formList[this.data.form.cusIndex].componentValue
    this.dealCheckCustomer(sync, index, value, cusValue)
  },
  dealCheckCustomer(sync, index, value, cusValue) {
    if (!sync) {
      if (this.data.cusName && this.data.phoneValue) {
        this.checkExist(index)
      } else {
        value = Object.assign(value, {
          sync: sync
        })
        cusValue = Object.assign(cusValue, {
          sync: sync
        })
        // this.data.form.formList[index].componentValue = value
        this.data.form.formList[index] = value
        this.data.form.formList[this.data.form.cusIndex].componentValue = cusValue
        this.setData({
          'form.formList': this.data.form.formList
        })
        wx.showToast({
          title: "请填写联系电话、客户名称!",
          icon: "none"
        })
        return
      }
    } else {
      value = Object.assign(value, {
        sync: !sync
      })
      cusValue = Object.assign(cusValue, {
        sync: !sync
      })
      // this.data.form.formList[index].componentValue = value
      this.data.form.formList[index] = value
      this.data.form.formList[this.data.form.cusIndex].componentValue = cusValue
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  checkExist(index) {
    let url = _config.url.check_phone.replace('{phone}', this.data.phoneValue),
      value = this.data.form.formList[index],
      cusValue = this.data.form.formList[this.data.form.cusIndex].componentValue
    _fetch.get(url).then(res => {
      if (res) {
        wx.showToast({
          title: "客户表中已存在该客户!",
          icon: "none"
        })
      }
      value = Object.assign(value, {
        sync: !res
      })
      cusValue = Object.assign(cusValue, {
        sync: !res
      })
      // this.data.form.formList[index].componentValue = value
      this.data.form.formList[index] = value
      this.data.form.formList[this.data.form.cusIndex].componentValue = cusValue
      this.setData({
        'form.formList': this.data.form.formList
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none',
      })
    })
  },
  tapCheck(e) {
    if (!this.data.isChange) {
      let index = e.currentTarget.dataset.iindex,
        name = e.currentTarget.dataset.name,
        value = this.data.form.formList[index].componentValue || [],
        arr
      arr = this.data.form.formList[index].checkList.map(i => {
        if (i.name === name) {
          return {
            name: i.name,
            checked: !value.includes(name)
          }
        } else {
          return i
        }
      })
      this.data.form.formList[index].checkList = arr
      let arr1 = arr.filter(i => {
        return i.checked
      })
      this.data.form.formList[index].componentValue = arr1.map(i => i.name)
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  tabRadio(e) {
    if (!this.data.isChange) {
      let index = e.currentTarget.dataset.iindex,
        name = e.currentTarget.dataset.name,
        arr
      arr = this.data.form.formList[index].checkList.map(i => {
        if (i.name == name) {
          i.checked = true
        } else {
          i.checked = false
        }
        return i
      })
      this.data.form.formList[index].checkList = arr
      this.data.form.formList[index].componentValue = name
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  checkRadioChange(e) {
    // 单/多选选择
    let index = e.currentTarget.dataset.iindex,
      arr
    if (e.detail.value && index !== null && index !== undefined) {
      if (this.data.form.formList[index].componentType === 3 || this.data.form.formList[index].componentType === 21) {
        arr = this.data.form.formList[index].checkList.map(i => {
          if (i.name == e.detail.value) {
            i.checked = true
          } else {
            i.checked = false
          }
          return i
        })
        this.data.form.formList[index].checkList = arr
      } else {
        arr = this.data.form.formList[index].checkList.map(i => {
          return {
            name: i.name,
            checked: e.detail.value.includes(i.name)
          }
        })
        this.data.form.formList[index].checkList = arr
      }
      this.data.form.formList[index].componentValue = e.detail.value
      this.setData({
        isChange: true,
        'form.formList': this.data.form.formList
      })
      setTimeout(() => {
        this.setData({
          isChange: false
        })
      }, 500);
    }
  },
  bindPicker(e) {
    // 下拉选择
    let index = e.currentTarget.dataset.iindex
    if (e.detail.value && index !== null && index !== undefined) {
      this.data.form.formList[index].componentValue = this.data.form.formList[index].optValue[Number(e.detail.value)]
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  bindProPicker(e) {
    // 服务项目下拉
    let index = e.currentTarget.dataset.iindex
    if (e.detail.value && index !== null && index !== undefined) {
      this.data.form.formList[index].componentValue = this.data.form.formList[index].checkList[Number(e.detail.value)]
      this.data.form.formList[index].showText = this.data.form.formList[index].checkList[Number(e.detail.value)].projectName
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  delImg(e) {
    //删除图片
    if (e.currentTarget.dataset.dindex !== null && e.currentTarget.dataset.dindex !== undefined) {
      let delIndex = Number(e.currentTarget.dataset.dindex)
      let imgIndex = e.currentTarget.dataset.iindex
      this.data.form.formList[imgIndex].componentValue.splice(delIndex, 1)
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  uploadImg(e) {
    // 上传图片
    let that = this
    let index = e.currentTarget.dataset.iindex
    let maxNum = 9 - this.data.form.formList[index].componentValue.length
    wx.chooseImage({
      count: maxNum,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        _fetch.get(_config.url.qiniu_token).then(function (data) {
          res.tempFilePaths.map(i => {
            wx.uploadFile({
              url: data.qiniuZone.upUrls[0],
              name: 'file',
              filePath: i,
              method: 'POST',
              header: {
                "Content-Type": "multipart/form-data"
              },
              formData: {
                token: data.token,
              },
              success: function (resp) {
                let hash = JSON.parse(resp.data).hash
                that.data.form.formList[index].componentValue = that.data.form.formList[index].componentValue.concat([data.domainUrl + '/' + hash])
                that.setData({
                  'form.formList': that.data.form.formList
                })
              },
              fail: function () {},
              complete: function () {},
            })
          })
        })
      }
    })
  },
  changeDateTimeMin(e) {
    // 时间选择
    let time = timeDateChoose.changeDateTimeMin(e)
    let index = e.currentTarget.dataset.iindex
    let timeArr = this.data.form.dateTimeArrayMin
    let arrIndex = time
    this.setData({
      'form.dateTimeMin': time
    })
    let dateTimeTemp = timeArr[0][arrIndex[0]] + '-' + timeArr[1][arrIndex[1]] + '-' + timeArr[2][arrIndex[2]] + ' ' + timeArr[3][arrIndex[3]] + ':' + timeArr[4][arrIndex[4]]
    let dateTime = app.globalData.isiOS ? (dateTimeTemp.replace('-', '/').replace('-', '/')) : dateTimeTemp
    this.data.form.formList[index].dateTimeMin = time
    let date = Number(new Date(dateTime))
    this.data.form.formList[index].componentValue = util.formatTime(date)
    this.setData({
      'form.formList': this.data.form.formList
    })
  },
  getCurrentLocatin(index) {
    // 获取定位
    let that = this
    wx.chooseLocation({
      success: function (res) {
        let locationString = res.latitude + "," + res.longitude;
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/',
          data: {
            "key": "3ESBZ-ZLBKK-PGZJ6-APQDW-APKMF-E5FSK",
            "location": locationString
          },
          method: 'GET',
          success: function (data) {
            that.data.form.formList[index].componentValue.addressValue = {
              'adCode': data.data.result.ad_info.adcode,
              'latitude': String(res.latitude),
              'longitude': String(res.longitude),
              'location': res.name,
            }
            that.data.form.formList[index].componentValue.addressType = 0
            that.data.form.formList[index].region = []
            that.setData({
              'form.formList': that.data.form.formList
            })
          }
        })
      }
    })
  },
  bindRegionChange(e) {
    // 更改地址
    if (e.detail.value && e.currentTarget.dataset.iindex) {
      let index = e.currentTarget.dataset.iindex
      this.data.form.formList[index].componentValue.addressValue = {
        provinceName: e.detail.value[0],
        cityName: e.detail.value[1],
        areaName: e.detail.value[2],
        provinceId: e.detail.code[0],
        cityId: e.detail.code[1],
        areaId: e.detail.code[2]
      }
      this.data.form.formList[index].componentValue.addressType = 1
      this.data.form.formList[index].region = e.detail.value
      this.setData({
        'form.formList': this.data.form.formList
      })
    }
  },
  settingCallback(res) {
    if (res.detail.authSetting['scope.userLocation']) {
      this.setData({
        applyLocationShow: false
      })
    }
  },
  openMap(e) {
    // 打开地图
    let that = this
    wx.getSetting({ //请求授权
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.getCurrentLocatin(e.currentTarget.dataset.iindex)
            },
            fail() {
              that.setData({
                applyLocationShow: true
              })
            }
          })
        } else {
          that.getCurrentLocatin(e.currentTarget.dataset.iindex)
        }
      },
      fail() {
        that.setData({
          applyLocationShow: true
        })
      }
    })
  },
  formSubmit(e) {
    console.log(e)
    let flag = true
    let list = JSON.stringify(this.data.form.formList)
    let arr = JSON.parse(list).map(i => {
      if (i.isRequired === 1) {
        if (i.componentValue === null || i.componentValue === undefined || i.componentValue === '') {
          wx.showToast({
            title: `${i.title}必填`,
            icon: 'none',
          });
          flag = false
        }
      }
      if (i.componentValue) {
        if (i.componentType === 8 || i.componentType === 20 || i.componentType === 22 || (i.componentType === 4 && Array.isArray(i.componentValue))) {
          if (i.componentType === 8) {
            if (i.componentValue.addressType !== null && i.componentValue.addressType !== undefined) {
              i.componentValue = JSON.stringify(i.componentValue)
            } else {
              i.componentValue = null
            }
          } else {
            i.componentValue = JSON.stringify(i.componentValue)
          }
        }
        if (i.componentType === 6) {
          i.componentValue = i.componentValue.join(',')
        }
      }
      return i
    })
    let url = _config.url.add_work.replace('{id}', this.data.templateId);
    let requestData = arr
    let formIds = [e.detail.formId]
    if (flag) {
      _fetch.post(url, requestData).then(() => {
        wx.reLaunch({
          url: '../order/index'
        })
      }).catch(error => {
        wx.showToast({
          title: error.smg,
          icon: 'none',
        });
      })
      _fetch.post(_config.url.send_form_id, formIds).then(() => {}).catch(error => {
        wx.showToast({
          title: error.smg,
          icon: 'none',
        });
      })
    }
  }
})